package com.example.tms.service;

import java.time.LocalDateTime;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.example.tms.dto.LoginRequest;
import com.example.tms.dto.LoginResponse;
import com.example.tms.entity.Employee;
import com.example.tms.entity.SystemLog;
import com.example.tms.mapper.SystemLogMapper;
import com.example.tms.util.JwtTokenUtil;

import jakarta.servlet.http.HttpServletRequest;

@Service
public class AuthService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private SystemLogMapper systemLogMapper;

    public LoginResponse login(LoginRequest loginRequest) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            // 先验证用户是否存在
            Employee employee = (Employee) userDetailsService.loadUserByUsername(loginRequest.getPhone());
            
            // 验证密码
            if (!passwordEncoder.matches(loginRequest.getPassword(), employee.getPassword())) {
                throw new BadCredentialsException("密码错误");
            }

            // 生成token
            Authentication authentication = new UsernamePasswordAuthenticationToken(
                employee, null, employee.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String token = jwtTokenUtil.generateToken(employee);
            
            // 记录登录日志
            SystemLog loginLog = new SystemLog();
            loginLog.setLevel("INFO");
            loginLog.setAction("用户登录");
            loginLog.setUserId(employee.getId().toString());
            loginLog.setIp(getClientIp(request));
            loginLog.setCreatedAt(LocalDateTime.now().toString());
            systemLogMapper.insert(loginLog);
            
            return new LoginResponse(token, employee);
        } catch (UsernameNotFoundException e) {
            throw new UsernameNotFoundException("用户不存在");
        } catch (BadCredentialsException e) {
            throw new BadCredentialsException("密码错误");
        } catch (Exception e) {
            throw new RuntimeException("登录失败: " + e.getMessage());
        }
    }
    
    private String getClientIp(HttpServletRequest request) {
        return Optional.ofNullable(request.getHeader("X-Forwarded-For"))
                .map(xff -> xff.split(",")[0].trim())
                .orElse(request.getRemoteAddr());
    }
}
